<template>
  <div class="activity-content" >
    <template v-for="(item, index) in productList">
      <div class="activity-item">
        <span v-if="item.personalLimited" class="discount-card" >人均限购{{item.personalLimitNum}}件</span>
        <div class="sell-out" v-if="fielsStatus === 2">
          <img class="sell-out-img" src="../img/bargainlimit.png" />
          <router-link tag="span" v-if="item.oldGoodsId"
          class="btn-yellow-over pro-over-pos"
          :to="{name: 'productDetail', params: {commodityID: item.oldGoodsId}, query: {keyword: $route.query.keyword}}" >查看原价商品</router-link>
        </div>
        <!-- oldGoodsId -->
        <div class="sell-out" v-else-if="item.stockLimit && item.stock < 1">
          <img class="sell-out-img" src="../img/sellnull.png" />
          <router-link tag="span" v-if="item.oldGoodsId"
          class="btn-yellow-over pro-over-pos"
          :to="{name: 'productDetail', params: {commodityID: item.oldGoodsId}, query: {keyword: $route.query.keyword}}" >查看原价商品</router-link>
        </div>
        <div class="pointer" @click="goToActive(item)">
          <div class="preview-img">
            <img class="img" :src="prefixImg + item.image" @error="catchErrorImage($event)"/>
          </div>
          <div class="pro-info txt-center">
            <h3 class="pro-name ellipsis">{{item.goodsName}} {{item.brandName}}</h3>
            <h4 class="pro-type">{{item.standard}}</h4>
          </div>
        </div>
        <div class="price-box">
          <div class="price">
            <template v-if="loginStatus === 1">
              <template v-if="item.pmtPrice > 0">
                <span class="now">￥{{item.pmtPrice | floatPrices}}</span>
                <span class="old" >￥{{item.price | floatPrices}}</span>
              </template>
              <span class="now" v-else>￥{{item.price | floatPrices}}</span>
              <span class="left blue">剩{{item.stockLimit ? item.stock : '9999'}}件</span>
            </template>
            <p class="txt-center ft-14" v-else-if="loginStatus === 4">登录后查看价格</p>
            <p class="txt-center ft-14" v-else>审核通过可查看</p>
          </div>
          <el-input-number class="input-num-self input-num-self-barginactivity" :title="`包装数${item.packingNum}`"
            v-if="fielsStatus === 1"
            size="mini"
            @keydown.110.native.prevent=""
            v-model="numList[index]"
            :min="0"
            :max="item.stockLimit ? (item.personalLimited ? item.lastPersonalLimitNum : item.stock) : 99999"
            :step="item.packingNum"
            :ref="`pro_${index}`"
            @change="debounceChangeProNum($event, index, item.packingNum, item)" >
          </el-input-number>
          <button v-show="fielsStatus === 1" class="btn-buy-red" @click="timeAddShopcart(item.productId, index, item)" :ref="`buy_${index}`">立即抢购</button>
          <button class="btn-buy"
            v-if="fielsStatus !== 1"
          :disabled="fielsStatus !== 1"
          @click="timeAddShopcart(item.productId, index, item)"
          >{{item.startTime,item.endTime | btnType}}</button>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import {prefixImg} from '@/tool/index'
import {InputNumber} from 'element-ui'
import { mapState, mapActions } from 'vuex'
import {changeProNumber} from '@/service/get-data'
import {eventBus} from '@/tool/events-bus'
import _ from 'lodash'

export default {
  name: 'FullProduct',
  components: {
    elInputNumber: InputNumber
  },
  props: {
    productList: {
      type: Array || Object,
      default: []
    },
    fielsStatus: {
      type: Number
    },
    actDate: {
      type: String
    }
  },
  data () {
    return {
      purchaseNum: 0, // 购买的数量
      numList: [],
      flag: true,
      changeflag: true,
      globalTimer: null
    }
  },
  computed: {
    prefixImg () {
      return prefixImg
    },
    loginStatus () {
      return this.$store.getters.loginStatus - 0
    },
    keyword () {
      return this.$route.query.keyword
    },
    proLen () {
      return this.productList && this.productList.length
    },
    ...mapState({
      limitArr: state => state.shopcart.limitArr,
      shopcartId: state => state.shopcart.shopCartId
    })
  },
  methods: {
    ...mapActions(['fetchCartList', 'fetchOpenActivity']),
    catchErrorImage (e) {
      e.target.src = require('img/newload.png')
    },
    debounceActive () {
      this.goToActive = _.debounce(function (item) {
        if (item.stock < 1 || this.fielsStatus !== 1) {
          this.$message(`${this.actDate}`)
          return
        }
        this.$router.push({name: 'productDetail', params: {commodityID: item.goodsId}, query: {keyword: this.$route.query.keyword}})
      }, 1000, {leading: true, trailing: false})
    },
    changeNumber (value) {
      const vm = this
      if (value > 20) {
        this.$nextTick(() => {
          vm.$refs['number'].$refs.input.setCurrentValue(5)
        })
      }
    },
    debounceChangeProNum (value, skuIndex, step, objitem) {
      this.debouncePro(value, skuIndex, step, objitem)
    },
    // 添加到购物车
    async addShopcat (proId, skuIndex, objitem) {
      if (this.loginStatus !== 1) return
      if (objitem.lastPersonalLimitNum === 0) {
        this.$message('您已达个人限购数量')
        return
      }
      // 添加到购物车
      let purchaseNum = this.numList[skuIndex]
      if (!purchaseNum) {
        return
      }
      let vm = this
      let surplusNum
      let shopcatNum
      if (objitem.personalLimited && objitem.lastPersonalLimitNum > 0) {
        this.limitArr.map((limitItm, limitInd) => {
          if (objitem.productId === limitItm.pid) {
            shopcatNum = limitItm.num
          }
        })
        surplusNum = objitem.lastPersonalLimitNum - shopcatNum
        if (surplusNum <= 0) {
          setTimeout(() => {
            this.numList[skuIndex] = 0
            vm.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
          }, 200)
          this.$message.error('抱歉,您抢购的商品已达购买上限')
          return
        }
      }
      let res = await changeProNumber(this.shopcartId, proId, '', purchaseNum, 0)
      // _arr['productList'][skuIndex]['number'] = leftNum
      if (res.data.resultCode && res.data.resultCode === 2000) {
        // let endTime = objitem.endTime.split(' ')[1].substr(0, 5)
        this.$alert(`恭喜您，抢购成功~ `, '抢购成功', {
          showClose: false
        })
        eventBus.$emit('show:pop')
        this.numList[skuIndex] = 0
        this.$nextTick(() => {
          vm.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
        })
        this.fetchCartList() // 更新购物车列表
        this.$emit('refresh') // 更新库存（更新商品列表）
        // this.$message({message: '已经添加货品的数量到购物车'})
      } else {
        this.$message.error({
          message: res.data.resultMsg
        })
      }
    },
    timeAddShopcart (proId, skuIndex, objitem) {
      if (this.flag) {
        this.addShopcat(proId, skuIndex, objitem)
      }
      this.flag = false
      setTimeout(() => {
        this.flag = true
      }, 300)
    },
    debounceStepNum () {
      this.debouncePro = _.debounce(function (value, skuIndex, step, objitem) {
        // 未登录或审核未通过
        if (this.loginStatus !== 1) {
          this.$message('您还未登陆或未审核通过')
          return
        }
        // 如果不存在id请求购物车
        if (!this.shopcartId) {
          this.fetchCartList()
        }
        if (value === 0) return // 产品数量为0
        let shopcatNum = 0 // 已加入购物车的数量
        let surplusNum // 去掉购物车数量的剩余可购买数量
        // 包装盒倍数
        let lastNum = value % step
        let leftNum = lastNum === 0 ? value : value - lastNum + step
        // 判断包装盒数
        if (lastNum !== 0) {
          this.$message(`您当前选择的商品是${step}件一起采购哦`)
        }
        // 个人限购 商品不限购
        if (objitem.personalLimited) {
          this.limitArr.map((limitItm, limitInd) => {
            if (objitem.productId === limitItm.pid) {
              shopcatNum = limitItm.num
            }
          })
          surplusNum = objitem.lastPersonalLimitNum - shopcatNum
          // 购物存货和限购数量一样 或 个人限购剩余数量为0
          if (surplusNum === 0 || objitem.lastPersonalLimitNum === 0) {
            this.$nextTick(() => {
              this.numList[skuIndex] = 0
              this.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
            })
            this.$message(`抱歉,此商品限购期间每人限购${objitem.personalLimitNum}件,您已达此商品的添加上限`)
          // 输入数量大于可购数量
          } else if (surplusNum > 0 && leftNum > surplusNum) {
            if (objitem.stockLimit && surplusNum > objitem.stock) {
              this.$nextTick(() => {
                this.numList[skuIndex] = objitem.stock
                this.$refs[`pro_${skuIndex}`][0].setCurrentValue(objitem.stock)
              })
              this.$message(`您的选购数量已达库存数量`)
              return
            } else {
              this.$nextTick(() => {
                this.numList[skuIndex] = surplusNum
                this.$refs[`pro_${skuIndex}`][0].setCurrentValue(surplusNum)
              })
              this.$message('您的选购数量已达上限')
              return
            }
          }
        }
        // 商品限购
        if (objitem.stockLimit && leftNum > objitem.stock) {
          this.$message('您的选购数量已达库存数量')
          this.$nextTick(() => {
            this.numList[skuIndex] = objitem.stock
            this.$refs[`pro_${skuIndex}`][0].setCurrentValue(objitem.stock)
          })
          leftNum = objitem.stock
        } else {
          this.$nextTick(() => {
            this.numList[skuIndex] = leftNum
            this.$refs[`pro_${skuIndex}`][0].setCurrentValue(leftNum)
          })
        }
      }, 300, {leading: true, trailing: false})
    }
  },
  filters: {
    btnType (timeS, timeE) {
      let now = new Date()
      let getTime = now.getTime()
      let startTime = new Date(timeS.replace(/-/g, '/'))
      let endTime = new Date(timeE.replace(/-/g, '/'))
      let time1 = startTime.getTime()
      let time2 = endTime.getTime()
      let month = startTime.getMonth() + 1
      let day = startTime.getDate()
      let hour = String(startTime.getHours())
      let minute = String(startTime.getMinutes())
      if (hour.length < 2) {
        hour = '0' + hour
      }
      if (minute.length < 2) {
        minute = '0' + minute
      }
      if (getTime < time1) {
        // return String(hour) + ':' + String(minute) + '开启'
        if (month !== now.getMonth() + 1 || day !== now.getDate()) {
          month = month + ''
          day = day + ''
          if (month.length < 2) {
            month = '0' + month
          }
          if (day.length < 2) {
            day = '0' + day
          }
          return month + '月' + day + '日开启 敬请期待'
        } else {
          return hour + ':' + minute + '开启 敬请期待'
        }
      } else if (getTime >= time1 && getTime < time2) {
        return '立即抢购'
      } else if (getTime >= time2) {
        return String(hour) + ':' + String(minute) + '场已结束'
      }
    }
  },
  mounted () {
    let arr = new Array(this.proLen).fill(0)
    this.numList = JSON.parse(JSON.stringify(arr))
    this.debounceStepNum()
    this.debounceActive()
  },
  watch: {
    productList (value) {
      let len = value && value.length
      let arr = new Array(len).fill(0)
      this.numList = arr
    }
  }
}
</script>
<style lang="scss">
  .el-input-number--mini{
    width: 100px;
  }
</style>

<style lang="scss" scoped>
  .activity-content{
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
  }
  .activity-item{
      position: relative;
      width: 230px;
      margin-bottom: 10px;
      padding: 0 20px 16px;
      font-size: 0;
      display: inline-block;
      background: #FFFFFF;
      margin-right: 10px;
      -webkit-transition: all 0.2s linear;
      transition: all 0.2s linear;
      overflow: hidden;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
    &:nth-child(5n){
      margin-right: 0;
    }
    .stock-num{
      display:inline-block;
      padding: 0 10px;
      line-height: 2;
      font-size: 14px;
      background: #413d3d;
      color: #ffffff;
    }
    .preview-img{
      height: 170px;
      width: 170px;
      margin: 0 auto 12px;
      .img{
        width: 100%;
        height: 100%;
        vertical-align: middle
      }
    }
    .pro-name{
      color: #474747;
      font-size: 14px;
      line-height: 20px;
      margin-bottom: 4px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
    .pro-type{
      color: #999999;
      font-size: 12px;
      line-height: 14px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
    .price-box{
      margin-top: 12px;
      padding-bottom: 2px;
      // border-top: 1px solid rgba(220,220,220, .2);
      // padding-top: 16px;
    }
    .price{
      margin-bottom: 20px;
      font-size: 0;
    }
    .old{
      color: #bdbdbd;
      font-size: 12px;
      text-decoration: line-through;
    }
    .now{
      font-family:PingFangSC-Medium;
      display: inline-block;
      font-size: 18px;
      padding-right: 3px;
      color: #FF0100;
    }
    .old{
      color: #bdbdbd;
      font-size: 12px;
      text-decoration: line-through;
    }
    .left{
      float: right;
      color: #666;
      font-size: 14px;
      margin-top: 2px;
    }
    .btn-buy-red{
      float:right;
      width:88px;
      height: 30px;
      border-radius: 4px;
      line-height: 30px;
      text-align:center;
      color: #ffffff;
      background: #FF6546;
      border:none;
      font-size:14px;
    }
    .btn-buy{
      // display: inline-block;
      text-align: center;
      color: #FF0000;
      border-radius: 2px;
      font-size: 14px;
      line-height: 25px;
      border: 1px solid #FF0000;
      background: #fff;
      margin-bottom: 2px;
      width: 192px;
      float: right;
      cursor: pointer;
    }
    .btn-buy2{
      width: 86px;
      color: #fff;
      background: #FF0000;
    }
    .btn-buy3{
      color: #666666;
      border: 1px solid #666666;
    }
    .btn-disabled{
      color: #999;
      border: 1px solid #ddd;
      background: #f0f0f0;
      cursor: not-allowed;
    }
    .cannot-buy{
      display:block;
      // width: 100%;
      // height:40px;
      text-align: center;
      color: #ffffff;
      background: #dfdfdf;
      // border-radius: 2px;
      // font-size: 16px;
      // line-height: 40px;
    }
    .sell-out{
      position:absolute;
      left:0;
      top:0;
      bottom: 0;
      right: 0;
      background: rgba(0,0,0,.63);
      z-index: 88;
      .sell-out-img{
        left: 50%;
        transform: translateX(-50%);
        position: absolute;
        top: 76px;
      }
    }
  }
    .btn-yellow-over{
      display: inline-block;
      width:130px;
      height:40px;
      font-size:14px;
      color:rgba(51,51,51,1);
      text-align: center;
      line-height: 40px;
      background:rgba(251,205,59,1);
      border-radius:6px;
    }
    .pro-over-pos{
      position: absolute;
      bottom: 36px;
      left: 50%;
      margin-left: -65px;
      cursor: pointer;
    }
    // 首页的item
    .product-index-item{
        position: relative;
        width: 392px;
        margin-bottom: 10px;
        padding: 30px 20px 33px 30px;
        font-size: 0;
        display: inline-block;
        background: #fff;
        border-radius: 2px;
        margin-right: 12px;
        -webkit-transition: all 0.2s linear;
        transition: all 0.2s linear;
        overflow: hidden;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
      &:nth-child(3n){
          margin-right: 0;
        }
      .activity-left{
        float: left;
        width: 140px
      }
      .activity-right{
        margin-left: 140px;
      }
      .stock-num{
        display:inline-block;
        padding: 0 10px;
        line-height: 2;
        font-size: 14px;
        background: #413d3d;
        color: #ffffff;
      }
      .preview-img{
        height: 120px;
        width: 120px;
        margin-top: 15px;
        .img{
          width: 100%;
          height: 100%;
          vertical-align: middle
        }
      }
      .pro-name{
        font-family:PingFangSC-Medium;
        margin-bottom: 5px;
        color: #666;
        font-size: 18px;
        line-height: 25px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
      }
      .pro-type{
        color: #999999;
        font-size: 14px;
        line-height: 25px;
        margin-bottom: 5px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
      }
      .price-box{
        // margin-top: 12px;
        padding-bottom: 2px;
      }
      .price{
        margin-bottom: 5px;
        font-size: 0;
      }
      .old{
        color: #bdbdbd;
        font-size: 12px;
        text-decoration: line-through;
        vertical-align: middle;
      }
      .now{
        display: inline-block;
        font-size: 16px;
        padding-right: 3px;
        color: #ff0f34;
        vertical-align: middle;
      }
      .left{
        color: #666;
        font-size: 12px;
      }
      .activity-number{
        margin-bottom: 6px;
        overflow: hidden;
        line-height: 20px;
      }
      .input-num-self-activity{
        float: right;
        width: 88px;
        height: 20px;
        line-height: 20px;
        overflow: hidden;
      }
      .btn-buy{
        text-align: center;
        color: #FF0000;
        border-radius: 2px;
        font-size: 14px;
        line-height: 25px;
        border: 1px solid #FF0000;
        background: #fff;
        margin-bottom: 2px;
        width: 100%;
        cursor: pointer;
      }
      .circle-btn-buy{
        color: #FFF;
        background: #FF0000;
      }

      .btn-disabled{
        color: #666;
        border: 1px solid #666;
        cursor: not-allowed;
      }
      .cannot-buy{
        display:block;
        // width: 100%;
        // height:40px;
        text-align: center;
        color: #ffffff;
        background: #dfdfdf;
        // border-radius: 2px;
        // font-size: 16px;
        // line-height: 40px;
      }
      .sell-out{
        position:absolute;
        left:0;
        top:0;
        bottom: 0;
        right: 0;
        background: rgba(0,0,0,.63);
        z-index: 88;
        .sell-out-img{
          left: 50%;
          transform: translateX(-50%);
          position: absolute;
          top: 9px;
        }
      }
    }
</style>
<style lang="scss">
  .input-num-self-barginactivity {
    width: 88px!important;
      .el-input__inner{
        padding-left: 27px!important;
        padding-right: 27px!important;
      }
      .el-input-number__increase,.el-input-number__decrease {
        width: 26px;
        background: transparent!important;
      }
  }
  .input-num-self-activity{
    .el-input__inner{
      height: 20px;
      width: 88px;
      padding-left: 24px!important;
      padding-right: 24px!important;
      font-size: 16px;
      line-height: 20px;
      border-radius: 4px;
      color: #666;
      border: 1px solid #CBCBCB;
      background: transparent!important;
    }
    .el-input-number__decrease{
      border-radius: 4px 0 0 4px;
    }
    .el-input-number__increase{
      border-radius: 0 4px 4px 0;
    }
    .el-input-number__increase, .el-input-number__decrease {
      background: transparent!important;
      width: 24px;
      font-size: 12px
    }
    .el-input-number__increase.is-disabled, .el-input-number__decrease.is-disabled {
      color: #CBCBCB;
      background: transparent!important;
    }
  }

</style>

